| 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167 |
1
1
1
1
1
6
6
1
1
6
84207
1
23
1
5
5
1
1
1
1
1
1
1
1
1
1
1
1
1
8
2
6
6
12
12
12
6
1
1
1
1289
1
1
2
14
14
2
1
3
3
10
3
1
2489
24313
24313
2489
1
11601
11601
9778
9778
11601
2529
2529
1
2845
2845
3771
3771
1
1200
1200
1198
1198
2396
1
124
124
124
132
5
127
1
3618
3618
3490
128
128
132
132
132
132
132
1
44861
44861
44859
1
6021
2400
2400
6021
6021
174025
174025
174025
174022
3
3
3
1
1200
1200
1200
1200
1200
1200
1200
1
1200
1200
1
1200
1200
1099
1200
1172
1172
1
1171
1195
3
1192
1
1191
1
1190
1
1189
1189
1189
1189
63
63
1
62
1188
1188
1188
1175
1175
1175
1175
1175
1175
11
11
11
11
11
11
1
1
1
1
18
6
12
12
12
12
1
1198
1198
1198
1
4
4
2
2
2
2
2
2
2
1
1186
1186
1152
34
34
34
2
32
2
30
30
30
30
1
1200
1200
1
1199
1188
1188
1188
1188
1188
1188
1188
1
1188
11
1
41241
41240
41240
41240
41240
41230
41230
170396
170396
170396
170396
170396
170396
10
9
41240
41240
40053
40053
1187
1
1187
1
27
27
1
1
1
1
1
1
1
4
4
4
4
4
1
1
1289
1289
1
92
3
89
1
89
34
34
34
1
12
12
11
12
12
1
11
1
1
1
1
1
1
1
1
50000
50000
50000
50000
1
1
1
1
1
1
1
1
1
1
1
1
50000
50000
50000
50000
1
1
1
1
50
50
1
11
7
7
7
7
1
7
7
2203
2203
2203
7
7
7
1
1
1
1
1
18
14
101111
4
2
1099
1099
2
2
1
1
65
65
65
1
102214
102214
104402
102214
1
102230
102230
102306
102306
102306
102297
102306
95
95
95
102306
102230
1
1
65
65
85
60
1
85
85
80
80
2
3
1
2
1
81
81
277
277
277
16
1
1
16
261
50
50
50
211
206
81
34
81
| /**
* @preserve
* Created by ANDREW on 10/10/2014.
* @requires 'bower_components/promise-polyfill'
*/
(function () {
'use strict';
/* jshint -W040 */
var root = typeof window === 'object' && window ? window : global,
__slice = [].slice,
__hasOwnProperty = {}.hasOwnProperty;
var type = (/**
*
* @returns {{isFunction(),isArray(),isBoolean(),isNumber(),isUndefined(),isObject()}}
*/
function () {
//noinspection JSUnusedAssignment
var result = {},
__toString = Object.prototype.toString,
_undef,
sourceTypes = [true, 1, [], function () {
}, _undef, {}],
classNamePattern = /\s+(\w+)]/,
fullName,
originalName; // PhantomJS bug
for (var i = 0, maxI = sourceTypes.length; i < maxI; i++) {
fullName = (originalName = __toString.call(sourceTypes[i])).replace('DOMWindow', 'Undefined'); // PhantomJS bug
result['is' + fullName.match(classNamePattern)[1]] = getTestFor(originalName);
}
//noinspection JSValidateTypes
return result;
function getTestFor(fullName) {
return function (val) {
return __toString.call(val) === fullName;
};
}
})();
/**
*
* @param val
* @returns {boolean}
*/
function isExecutable(val) {
return type.isFunction(val) || (val instanceof CrunchTask);
}
/**
*
* @throws Error
* @param errType
* @param msg
*/
function error(errType, msg) {
Iif (type.isUndefined(msg)) {
msg = errType;
errType = 'Generic';
}
throw new Error(['`CT_', errType, '`. Message: ', msg].join(''));
}
var Promise = ((typeof Promise !== 'undefined') ?
Promise :
((typeof root.Promise !== 'undefined') ?
root.Promise :
((typeof require !== 'undefined') ?
require("promise-polyfill") :
false)));
Iif (Promise === false) {
error('Linking', 'Dependency isn\'t met: "promise-polyfill"');
}
Iif (typeof module !== 'undefined' && module.exports) {
module.exports = root.CrunchTask ? root.CrunchTask : CrunchTask;
} else Eif (!root.CrunchTask) {
root.CrunchTask = CrunchTask;
}
var config = {
timeLimit: 100,
timeoutAmount: 0,
debug: false
}, defaultConfig = {
timeLimit: 100,
timeoutAmount: 0,
debug: false
},
staticParentTask = null,
staticSecurityLock = false,
staticLastSafeError = null;
/**
* @deprecated use range
* @type {staticFor}
*/
CrunchTask.for = staticFor;
CrunchTask.range = staticFor;
CrunchTask.rangeCheck = normalizeRanges;
/**
* @deprecated use range
* @type {staticFor}
*/
CrunchTask.rangeNextAndCheck = function(range, checkOnly) {
return range.canAdvance(checkOnly);
};
CrunchTask.forEach = staticForEach;
CrunchTask.reduce = staticReduce;
/**
*
* @param {{boolean}|{ timeLimit:Number, timeoutAmount:Number, debug:boolean }} obj
*/
CrunchTask.config = function(obj) {
if (!type.isObject(obj)) {
return CrunchTask.config(defaultConfig);
}
var result = {};
for (var prop in obj) {
//noinspection JSUnfilteredForInLoop
Eif (__hasOwnProperty.call(obj, prop) && __hasOwnProperty.call(config, prop)) {
//noinspection JSUnfilteredForInLoop
config[prop] = obj[prop];
//noinspection JSUnfilteredForInLoop
result[prop] = obj[prop];
}
}
return result;
};
CrunchTask.config(false);
var uid = 0;
/**
* Generates new id.
* @returns {number}
*/
function nextUid() {
return ++uid;
}
var EVENT_NAMES = _initObjectProps({
run : null,
done : null,
fail : null,
abort : null,
error : null,
progress: null,
idle : null
}, 'event.'),
STATE_NAMES = _initObjectProps({
init : null,
error : null,
running : null,
paused : null,
resolved: null,
rejected: null,
aborted : null
}, 'state.'),
SETTLED_STATES = _arrayToObject([
STATE_NAMES.error,
STATE_NAMES.resolved,
STATE_NAMES.rejected,
STATE_NAMES.aborted
], true),
NEED_REPEAT_STATES = _arrayToObject([
STATE_NAMES.running,
STATE_NAMES.paused
], true),
VERBOSE_STATES = _arrayToObject([
STATE_NAMES.resolved, STATE_NAMES.rejected,
STATE_NAMES.error, STATE_NAMES.aborted
], [
'success', 'failure',
'error', 'aborted'
]);
/**
* For each property assigns a value based on a prefix and the property name
* @param {object} obj
* @param {string} prefix
* @returns {object}
* @private
*/
function _initObjectProps(obj, prefix) {
for (var prop in obj) {
//noinspection JSUnfilteredForInLoop
Eif (__hasOwnProperty.call(obj, prop)) {
//noinspection JSUnfilteredForInLoop
obj[prop] = prefix + prop;
}
}
return obj;
}
/**
* Returns an object based on an array, where array's items from the property names, and the value is specified either directly, or corresponds to another array's item
* @param {[]} arr
* @param {[]|string|boolean} value
* @returns {{}}
* @private
*/
function _arrayToObject(arr, value) {
var result = {},
isArray = type.isArray(value);
for (var i = 0, iMax = arr.length; i < iMax; i++) {
result[arr[i]] = isArray ? value[i] : value;
}
return result;
}
function _objExtend(target, source) {
for (var prop in source) {
//noinspection JSUnfilteredForInLoop
Eif (__hasOwnProperty.call(source, prop)) {
//noinspection JSUnfilteredForInLoop
target[prop] = source[prop];
}
}
return target;
}
//noinspection JSCommentMatchesSignature,JSValidateJSDoc
/**
* Returns a partially applied function `fn` for optional `args`, with optional context of `ctx`
* @param {{}} [ctx]
* @param {function} fn
* @params {...*} args
* @returns {function} partially applied function
* @private
*/
function _fnPartial(/*{ctx}, fn, args..*/) {
var ctx = this,
fn = arguments[0],
args0 = __slice.call(arguments, 1);
if ((!type.isFunction(fn)) && (type.isFunction(args0[0]))) {
ctx = arguments[0];
fn = args0.shift();
}
return function () {
var args1 = __slice.call(arguments, 0);
return fn.apply(ctx, [].concat(args0, args1));
};
}
/**
* Executes the `fn` function in context of `ctx` and returns if result or `ctx` for chainability
* @param ctx
* @param fn
* @params {...*} args
* @returns {Function}|ctx
* @private
*/
function _fnBind(ctx, fn) {
var args0 = __slice.call(arguments, 2);
return function () {
var args1 = __slice.call(arguments, 0);
return fn.apply(ctx, [].concat(args0, args1)) || ctx;
};
}
/**
*
* @params {...function} fns
* @returns {Function}
* @private
*/
function _fnTogether(/* fns */) {
var auxFns = __slice.call(arguments, 0);
return function () {
var args = __slice.call(arguments, 0),
auxFn;
while ((auxFn = auxFns.shift()) && type.isFunction(auxFn)) {
auxFn.apply(this, args);
}
};
}
/**
* Subscribes a handler `fn(args..)` to a comma-separated event list. Events are scoped by the object `hive`
* @param hive
* @param evt
* @param fn*
* @private
*/
function _on(hive, evt, fn) {
Iif (!fn) {
return;
}
var args = __slice.call(arguments, 3),
evts = evt.split(/\s*,\s*/),
evtName,
handlers;
while ((evtName = evts.shift())) {
if ((handlers = hive[evtName])) {
handlers.push([fn, args]);
} else {
hive[evtName] = [[fn, args]];
}
}
}
/**
* Executes all subscribers for `evt` event, scoped by the `hive` object with the supplied arguments
* @param hive
* @param evt
* @params {...*} args
* @private
*/
function _trigger(hive, evt /*, args*/) {
var args1 = __slice.call(arguments, 2);
if (!hive[evt]) {
return;
}
var handlers = hive[evt];
for (var handler, args0, i = 0, maxI = handlers.length; i < maxI; i++) {
handler = handlers[i][0];
args0 = handlers[i][1];
Iif (!handler) {
continue;
}
try {
handler.apply(this, [].concat(args0, args1));
} catch (e) {
if (config.debug) {
console.log(e + ', stack: ' + e.stack);
}
}
}
}
/**
* Queues execution of this function asynchronously
* @param {number} timeoutAmount
* @param {function} fn
* @param {[]} [args0]
*/
function defer(timeoutAmount, fn, args0) {
var ctx = this;
return setTimeout(function () {
fn.apply(ctx, args0 || []);
}, timeoutAmount || 0);
}
/**
*
* @param {{}} [ctx]
* @param {function} fn
* @returns {function}
*/
function safe(ctx, fn) {
if (type.isFunction(ctx)) {
//noinspection JSValidateTypes
fn = ctx;
//noinspection JSValidateTypes
ctx = this;
}
Iif (!type.isFunction(fn)) {
fn = function () { };
}
return function () {
var args0 = __slice.call(arguments, 0);
try {
fn.apply(ctx, args0);
return true;
} catch (e) {
staticLastSafeError = e;
Iif (config.debug) {
console.log(e + ', stack: ' + e.stack);
}
return false;
}
};
}
/**
*
* @param descriptionFn
* @param taskEvents
* @returns {Promise}
*/
function protoRun(descriptionFn, taskEvents) {
var thisTask = this;
var parentTask = staticParentTask;
staticParentTask = null;
var instanceApi = {},
runCtx = {
task : thisTask,
id : 'T_' + thisTask.id + ':' + nextUid(),
conditionsToMeet: 1,
state : STATE_NAMES.init,
runBlock : 0,
runArgs : __slice.call(arguments, 2),
descriptionFn : descriptionFn,
parentTask : parentTask
},
encapsulation = null,
promiseFn = function (_resolve, _reject) {
encapsulation = _fnPartial(runCtx, encapsulateRunInstance,
instanceApi, taskEvents, {
resolve: _resolve,
reject : _reject
}
);
defer.call(runCtx, 0, proceedDescriptionFn, [instanceApi]);
};
return overloadPromise(new Promise(promiseFn), instanceApi, encapsulation);
}
function overloadPromise(promise, instanceApi, sealEncapsulationFn) {
sealEncapsulationFn(promise);
return _objExtend(promise, {
onError: _fnPartial(promise, instanceApi.runEventsOn, EVENT_NAMES.error),
abort : _fnPartial(promise, instanceApi.abort),
pause : _fnPartial(promise, instanceApi.pause),
resume: _fnPartial(promise, instanceApi.resume),
done : _fnPartial(promise, instanceApi.runEventsOn, EVENT_NAMES.done),
fail : _fnPartial(promise, instanceApi.runEventsOn, EVENT_NAMES.fail),
always: _fnPartial(promise, instanceApi.runEventsOn, [EVENT_NAMES.done, EVENT_NAMES.fail, EVENT_NAMES.error].join())
});
}
function encapsulateRunInstance(instanceApi, taskEvents, resolveReject, promise) {
var ctx = this,
thisTask = ctx.task,
parentTask = ctx.parentTask,
resolveSafe = safe(resolveReject.resolve),
rejectSafe = safe(resolveReject.reject),
runEvents = serveEvents(promise),
triggerBoth = _fnTogether(runEvents.trigger, taskEvents.trigger);
if (parentTask) {
parentTask.childTask = thisTask;
}
return _objExtend(instanceApi, {
/**
*
* @param _initFn
* @returns {*}
*/
setupInit: function (_initFn) {
Iif (SETTLED_STATES[ctx.state]) {
return;
}
if (!type.isUndefined(_initFn) && !type.isFunction(_initFn)) {
return signalError('CrunchTask.description.initSetup', 'Init setup expects an optional function.');
}
ctx.initFn = safe(thisTask, _initFn);
},
/**
*
* @param _bodyFn
* @param _needRepeat
* @param _timeout
* @returns {*}
*/
setupBody: function (_bodyFn, _needRepeat, _timeout) {
if (SETTLED_STATES[ctx.state]) {
return;
}
if (!type.isFunction(_bodyFn)) {
return signalError('CrunchTask.description.bodySetup', 'Body setup expects a function as a first optional arg.');
}
if (!type.isUndefined(_needRepeat) && !type.isBoolean(_needRepeat) && !type.isNumber(_needRepeat)) {
return signalError('CrunchTask.description.bodySetup', 'Body setup expects a number or false as a 2nd optional arg.');
}
if (!type.isUndefined(_timeout) && !type.isNumber(_timeout)) {
return signalError('CrunchTask.description.bodySetup', 'Body setup expects a number as a 3rd optional arg.');
}
ctx.bodyFn = safe(thisTask, _bodyFn);
ctx.conditionsToMeet--;
ctx.needRepeat = _needRepeat;
ctx.timeoutAmount = _timeout;
},
/**
*
* @param _finallyFn
* @returns {*}
*/
setupFin: function (_finallyFn) {
Iif (SETTLED_STATES[ctx.state]) {
return;
}
if (!type.isUndefined(_finallyFn) && !type.isFunction(_finallyFn)) {
return signalError('CrunchTask.description.finSetup', 'Fin setup expects a function as a first optional arg.');
}
ctx.finallyFn = safe(thisTask, _finallyFn);
},
signalError: signalError,
runEventsOn: runEvents.on,
//onError: _fnPartial(runEvents.on, EVENT_NAMES.error),
//onDone: _fnPartial(runEvents.on, EVENT_NAMES.done),
//onFail: _fnPartial(runEvents.on, EVENT_NAMES.fail),
//onAlways: _fnPartial(runEvents.on, [EVENT_NAMES.done,EVENT_NAMES.fail].join()),
/**
*
*/
goRunning: function () {
thisTask.runCount++;
ctx.state = STATE_NAMES.running;
taskEvents.trigger(EVENT_NAMES.run, ctx.id); // no need to call runInst
},
/**
*
*/
resolve : function () {
Iif (SETTLED_STATES[ctx.state]) {
return;
}
var args0 = __slice.call(arguments, 0);
ctx.state = STATE_NAMES.resolved;
ctx.value = args0;
decreaseRunning(thisTask);
signalGeneric(args0, EVENT_NAMES.done, resolveSafe);
},
/**
*
*/
reject : function () {
Iif (SETTLED_STATES[ctx.state]) {
return;
}
var args0 = __slice.call(arguments, 0);
ctx.state = STATE_NAMES.rejected;
ctx.value = args0;
decreaseRunning(thisTask);
signalGeneric(args0, EVENT_NAMES.fail, rejectSafe);
},
abort : function () {
Iif (SETTLED_STATES[ctx.state]) {
return;
}
ctx.state = STATE_NAMES.aborted;
return this;
},
pause: function () {
if (SETTLED_STATES[ctx.state]) {
return;
}
ctx.state = STATE_NAMES.paused;
return this;
},
resume: function () {
if (SETTLED_STATES[ctx.state]) {
return;
}
ctx.state = STATE_NAMES.running;
return this;
},
sendNotify: _fnPartial(triggerBoth, EVENT_NAMES.progress)
});
function signalError() {
if (SETTLED_STATES[ctx.state]) {
return;
}
var args0 = __slice.call(arguments, 0);
ctx.state = STATE_NAMES.error;
ctx.value = args0;
signalGeneric(args0, EVENT_NAMES.error, rejectSafe);
}
function signalGeneric(args0, eventName, actionFn) {
triggerBoth.apply(this, [eventName].concat(args0));
Eif (actionFn) {
defer.call(thisTask, 0, actionFn, [args0]);
}
}
function signalTwoParties(taskC, taskP) {
defer(1, function () {
if ((taskC.runCount + taskP.runCount) > 0) {
return;
}
staticSecurityLock = true;
taskC._signalIdle();
staticSecurityLock = true;
taskP._signalIdle();
delete ctx.parentTask;
delete taskP.childTask;
});
}
function decreaseRunning(thisTask) {
thisTask.runCount = Math.max(0, thisTask.runCount - 1);
if (thisTask.runCount) {
return;
}
delete thisTask.isAborted;
delete thisTask.isPaused;
if (thisTask.childTask) {
signalTwoParties(thisTask.childTask, thisTask);
} else if (ctx.parentTask) {
signalTwoParties(thisTask, ctx.parentTask);
} else {
defer(1, function() {
Iif (thisTask.runCount) {
return;
}
staticSecurityLock = true;
thisTask._signalIdle();
});
}
}
}
function proceedDescriptionFn(instanceApi) {
var ctx = this,
thisTask = ctx.task,
descriptionFn = ctx.descriptionFn;
if (!descriptionFn) {
return instanceApi.signalError('CrunchTask.description.empty', 'Description function is empty.');
}
if (safe(thisTask, descriptionFn)(
instanceApi.setupInit,
instanceApi.setupBody,
instanceApi.setupFin) &&
(!SETTLED_STATES[ctx.state]) &&
(ctx.conditionsToMeet === 0)) {
var _needRepeat = ctx.needRepeat;
_needRepeat = ((_needRepeat !== false) ? (_needRepeat || 0) : _needRepeat);
ctx.needRepeat = (_needRepeat === 0) ? true : _needRepeat;
ctx.timeoutAmount = ctx.timeoutAmount || 0;
instanceApi.goRunning();
// schedule init, body, fin, etc.
defer.call(ctx, 0, function () {
if (this.initFn && !this.initFn.apply(this, this.runArgs)) {
instanceApi.signalError('CrunchTask.description.init');
}
proceedBodyFn.call(this, instanceApi, true);
});
} else {
// bad outcome, reject
return instanceApi.signalError('CrunchTask.description.else', '');
}
}
function proceedBodyFn(instanceApi, isFirstTime) {
defer.call(this, isFirstTime ? 0 : this.timeoutAmount, function (instanceApi) {
var task = this.task,
needRepeat = this.needRepeat,
timeLimit = type.isNumber(needRepeat) ? needRepeat : 0;
var timerBatchStart,
timerStart,
miniRunCount = 0,
timerElapsed = 0;
var canExecuteNextLoop = (this.state === STATE_NAMES.running) && !task.isPaused && !task.isAborted,
canRepeatThisLoop,
canQueueNextBatch;
if (canExecuteNextLoop) {
timerBatchStart = new Date();
do {
try {
timerStart = new Date();
this.bodyFn(instanceApi.resolve, instanceApi.reject, instanceApi.sendNotify, {
batchStarted: timerBatchStart,
batchIndex : miniRunCount,
batchElapsed: timerElapsed,
runBlock : this.runBlock
});
} catch (ex) {
if (config.debug) {
console.log(ex + ', stack: ' + ex.stack);
}
instanceApi.signalError('body', ex);
}
timerElapsed += (new Date() - timerStart);
miniRunCount++;
canRepeatThisLoop = needRepeat && (timeLimit !== 0) &&
(timerElapsed < timeLimit) && (this.state === STATE_NAMES.running);
} while (canRepeatThisLoop);
} else if (task.isAborted || this.state === STATE_NAMES.aborted) {
instanceApi.reject('aborted');
}
canQueueNextBatch = needRepeat && NEED_REPEAT_STATES[this.state] && !task.isAborted;
if (canQueueNextBatch) {
this.runBlock++;
return proceedBodyFn.call(this, instanceApi);
}
if (needRepeat === false) {
instanceApi.resolve();
}
Iif (this.finallyFn && !this.finallyFn.call(this, VERBOSE_STATES[this.state])) {
instanceApi.signalError('CrunchTask.description.fin', this.status);
}
}, [instanceApi]);
}
function protoAbort() {
this.isAborted = true;
return this;
}
function protoPause() {
this.isPaused = true;
return this;
}
function protoResume() {
delete this.isPaused;
return this;
}
function protoThen(descriptionFn /*, tasks..*/){
var args0 = __slice.call(arguments, 1), _newTask;
try {
return (_newTask = new CrunchTask(descriptionFn));
} finally {
_newTask.done(doneHandler);
this.done(doneHandler);
}
function doneHandler() {
var args1 = __slice.call(arguments, 0), task;
while ((task = args0.shift())) {
getExecutableFor(task)(args1);
}
}
}
function serveEvents(ctx, _obj) {
var obj = _obj || {};
return {
on : _fnBind(ctx, _on, obj),
trigger: _fnBind(ctx, _trigger, obj)
};
}
/**
*
* @callback descriptionFunc
* @param {function} initSetup
* @param {function} bodySetup
* @param {function} finSetup
*/
/**
*
* @param {descriptionFunc} descriptionFn
* @returns {CrunchTask}
* @constructor
*/
function CrunchTask(descriptionFn) {
// always dealing with the `new` keyword instantiation
if (!(this instanceof CrunchTask)) {
return new CrunchTask(descriptionFn);
}
return prepareBlankTask(this, serveEvents(this), descriptionFn);
}
function prepareBlankTask(task, events, descriptionFn) {
return _objExtend(task, {
id : nextUid(),
timestamp: new Date() - 0,
runCount : 0,
isIdle : function isIdle() {
return task.runCount === 0;
},
pause : _fnBind(task, protoPause),
resume: _fnBind(task, protoResume),
abort : _fnBind(task, protoAbort),
run : _fnPartial(task, protoRun, descriptionFn, events),
then: _fnPartial(task, protoThen),
onRun : _fnPartial(events.on, EVENT_NAMES.run),
onIdle : _fnPartial(events.on, EVENT_NAMES.idle),
onError : _fnPartial(events.on, EVENT_NAMES.error),
done : _fnPartial(events.on, EVENT_NAMES.done),
fail : _fnPartial(events.on, EVENT_NAMES.fail),
always : _fnPartial(events.on, [EVENT_NAMES.done, EVENT_NAMES.fail, EVENT_NAMES.error].join()),
progress: _fnPartial(events.on, EVENT_NAMES.progress),
_signalIdle: function(){
Iif (!staticSecurityLock) { return; }
staticSecurityLock = false;
events.trigger(EVENT_NAMES.idle);
}
});
}
//noinspection JSCommentMatchesSignature,JSValidateJSDoc
/**
* @param {number} [start]
* @param {number} [finish]
* @param {number} [increment]
* @param {boolean} [inclusive]
* @param {function|CrunchTask} fnBody
* @param {function|CrunchTask} fnTail
* @returns {CrunchTask}
*/
function staticFor(/*{start, finish, increment, inclusive, } * n, fnBody, {fnTail}*/) {
var argsCount = arguments.length,
fnCount = 0;
while (isExecutable(arguments[argsCount - 1 - fnCount])) {
fnCount++;
}
var args = __slice.call(arguments, 0, argsCount - fnCount),
fns = __slice.call(arguments, -fnCount),
ranges = new Range(args),
taskBody = fns[0],
taskTail = fns[1] || function () {
};
if (!taskBody) {
return resolvedTask();
}
return internalFor(ranges, taskBody, taskTail);
}
function staticForEach(arr, taskBody, taskTail) {
return new CrunchTask(function (init, body, fin) {
var ranges,
ptr,
arrInternal = arr,
canRunCycle,
bodyFn = getExecutableFor(taskBody, this),
tailFn = getExecutableFor(taskTail, this);
init(function (_arr) {
Iif (_arr) {
arrInternal = arr;
}
ranges = new Range([0, arrInternal.length]);
canRunCycle = ranges.canAdvance(true);
});
body(function (resolve) {
Eif (canRunCycle) {
ptr = ranges.valueOf()[0];
bodyFn([arrInternal[ptr], ptr]);
}
if (!canRunCycle || !ranges.canAdvance()) {
resolve();
}
}, config.timeLimit, config.timeoutAmount);
fin(function () {
tailFn(ranges.valueOf());
});
});
}
function staticReduce(arr, memo, taskBody, taskTail) {
return new CrunchTask(function (init, body, fin) {
var ranges,
ptr,
arrInternal = arr,
memoInternal = memo,
canRunCycle,
bodyFn = getExecutableFor(taskBody, this),
tailFn = getExecutableFor(taskTail, this);
init(function (_arr, _memo) {
Iif (_arr) {
arrInternal = arr;
}
ranges = new Range([0, arrInternal.length]);
canRunCycle = ranges.canAdvance(true);
Iif (!type.isUndefined(_memo)) {
memoInternal = _memo;
}
});
body(function (resolve) {
Eif (canRunCycle) {
ptr = ranges.valueOf()[0];
memoInternal = bodyFn([memoInternal, arrInternal[ptr], ptr]);
}
if (!canRunCycle || !ranges.canAdvance()) {
resolve(memoInternal);
}
}, config.timeLimit, config.timeoutAmount);
fin(function () {
tailFn(memoInternal, ranges.valueOf());
});
});
}
function normalizeRanges() {
var args = __slice.call(arguments, 0);
return new Range(args);
}
function internalFor(_ranges, taskBody, taskTail) {
return new CrunchTask(function (init, body, fin) {
var ranges = _ranges, canRunCycle,
bodyFn = getExecutableFor(taskBody, this),
tailFn = getExecutableFor(taskTail, this);
init(function () {
var args = __slice.call(arguments, 0);
if (args.length) {
ranges = new Range(args);
}
canRunCycle = ranges.canAdvance(true);
});
body(function (resolve) {
Eif (canRunCycle) {
bodyFn(ranges.valueOf());
}
if (!canRunCycle || !ranges.canAdvance()) {
resolve();
}
}, config.timeLimit, config.timeoutAmount);
fin(function () {
tailFn(ranges.valueOf());
});
});
}
function resolvedTask() {
return new CrunchTask(function (init, body) {
body(function (resolve) {
resolve();
});
});
}
function getExecutableFor(task, ctx) {
if (type.isFunction(task)) {
return function (args) {
return task.apply(ctx || this, args);
};
} else if (task instanceof CrunchTask) {
return function (args) {
staticParentTask = ctx;
return task.run.apply(task, args);
};
} else {
return function (k) {
return k;
};
}
}
var Range = (function () {
function Range(args) {
Iif ((arguments.length > 1) || (!type.isArray(args))) {
error('Ranges', 'Pass strictly a single arguments of type array');
}
Iif (!(this instanceof Range)) {
return new Range(args);
}
this.data = translateRangeArgs(parseRangeArgs(args));
}
Range.prototype.toString = Range.prototype.valueOf = function () {
var result = [];
for (var i = 0, maxI = this.data.length; i < maxI; i++) {
result.push(this.data[i].current);
}
return result;
};
/**
*
* @param {boolean} [justCheck]
* @returns {boolean}
*/
Range.prototype.canAdvance = function canAdvance(justCheck) {
var currentR = 0,
ranges = this.data,
maxR = ranges.length,
range,
counterOverflow,
rangeInBounds;
do {
counterOverflow = false;
range = ranges[currentR];
if (justCheck !== true) {
range.current += range.step;
}
if ((!range.inclusive && (range.current === range.to)) || ((range.step > 0) ? (range.current > range.to) : (range.current < range.to))) {
range.current = range.from;
counterOverflow = true;
currentR++;
}
rangeInBounds = (currentR < maxR);
} while (counterOverflow && rangeInBounds);
return (!counterOverflow && rangeInBounds);
};
return Range;
function translateRangeArgs(args) {
var result = [];
for (var i = 0, maxI = args.length; i < maxI; i++) {
result.push(translateRangeSet(args[i]));
}
return result;
}
function translateRangeSet(rangeSet) {
var rangeLength = rangeSet.length,
last = rangeLength - 1,
lastIsBool = type.isBoolean(rangeSet[last]),
step;
//noinspection FallThroughInSwitchStatementJS
switch (rangeLength - ((lastIsBool) ? 1 : 0)) {
case 2: // fallthrough
case 3: // fallthrough
{
step = (((rangeLength - ((lastIsBool) ? 1 : 0)) === 3) ?
rangeSet[2] : ((rangeSet[0] <= rangeSet[1]) ? 1 : -1));
return {
from : rangeSet[0],
current : rangeSet[0],
to : rangeSet[1],
step : step,
inclusive: lastIsBool ? rangeSet[rangeLength - 1] : false
};
}
case 0: // fallthrough
case 1: // fallthrough
error('Ranges', 'Use at least two values to define a range.');
break;
default:
if (((rangeLength % 2) === 0) && ((rangeLength % 3) === 0)) {
error('Ranges', 'Use arrays to split range parts. Cannot determine pattern now.');
} else {
error('Ranges', 'Use arrays to split range parts properly.');
}
}
}
function parseRangeArgs(args, preventRecursion) {
var result = [],
current = [],
item,
isArrayFlag;
while (args.length) {
item = args.splice(0, 1)[0];
isArrayFlag = type.isArray(item);
if (isArrayFlag && (preventRecursion !== true)) {
if (current.length) {
result.push(current);
current = [];
}
result.push(parseRangeArgs(item, true));
} else if (type.isBoolean(item)) {
current.push(item);
result.push(current);
current = [];
} else if (type.isNumber(item)) {
current.push(item);
}
}
if (current.length) {
result.push(current);
}
return (preventRecursion === true) ? result[0] : result;
}
})();
})();
|